package helper

import "encoding/json"
import "net"
import (
	"fmt"
	"github.com/spf13/cast"
	"github.com/spf13/pflag"
	"time"
)

func JsonMarshal(v interface{}) []byte {
	b, err := json.Marshal(v)
	if err != nil {
		panic(err)
	}

	return b
}

func WriteMcpMsg(conn net.Conn, e error) {
	if e != nil {
		//return "!ERR xxx", because jmredisproxy need this to throw exception.
		conn.Write([]byte(fmt.Sprintf("!ERR %s\r\n", e)))
	} else {
		conn.Write([]byte(fmt.Sprintf("+OK\r\n")))
	}
}

type timeValue struct {
	f func(time.Duration)
	d time.Duration
}

func (v *timeValue) Set(val string) error {
	d, err := cast.ToDurationE(val)
	if err != nil {
		return err
	}

	v.d = d
	v.f(d)
	return nil
}

func (v *timeValue) Type() string {
	return "duration"
}

func (v *timeValue) String() string {
	return v.d.String()
}

func PflagTimeValue(f func(time.Duration), d time.Duration) pflag.Value {
	t := &timeValue{d: d, f: f}
	t.d = d
	t.f(d)
	return t
}
